/* ************************************************************************
> File Name:     doublelinkedlist.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年05月03日 星期二 20时55分10秒
> Description:   
 ************************************************************************/
#include<stdlib.h>
#include"doublelinkedlist.h"

struct node tailsentinel;
struct node headsentinel = {0, NULL, &tailsentinel};
struct node tailsentinel = {0, &headsentinel, NULL};

static link head = &headsentinel;
static link tail = &tailsentinel;

link make_node(unsigned char item)
{
    link p;
    p = malloc(sizeof *p);
    p->item = item;
    p->prev = NULL;
    p->next = NULL;

    return p;
}

void free_node(link p)
{
    free(p);
}

link search(unsigned char item)
{
    link p;
    for (p = head->next; p != tail; p = p->next){
        if (p->item == item){
            return p;
        }
    }
    return NULL;
}

void insert(link p)
{
    p->next = head->next;
    head->next->prev = p;
    head->next = p;
    p->prev = head;
}

void delete(link p)
{
    p->prev->next = p->next;
    p->next->prev = p->prev;
}

void traverse(void (*visit) (link))
{
    link p;
    for (p = head->next; p != tail; p = p->next){
        visit(p);
    }
}

void destroy(void)
{
    link p;
    for (p = head->next; p != tail;){
        link q = p->next;
        free_node(p);
        p = q;
    }
    head->next = tail;
    tail->prev = head;
}

void enqueue(link p)
{
    insert(p);
}

link dequeue(void)
{
    if (tail->prev == head){
        return NULL;
    }
    else{
        link p = tail->prev;
        delete(p);
        return p;
    }
}
